<%--
  Created by IntelliJ IDEA.
  User: zogod
  Date: 2016/9/8
  Time: 15:14
  To change this template use File | Settings | File Templates.
--%>
<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@page import="java.util.Random"%>
<%@page import="java.awt.Color"%>
<%@page import="org.patchca.service.ConfigurableCaptchaService" %>
<%@page import="org.patchca.color.SingleColorFactory" %>
<%@page import="org.patchca.filter.predefined.*" %>
<%@page import="java.io.FileOutputStream" %>
<%@page language="java" contentType="image/JPEG; charset=UTF-8" pageEncoding="UTF-8"%>
<%!
    //获取随机颜色
    Color getRandColor(int fc,int bc){
        Random random = new Random();
        if(fc>255) fc=255;
        if(bc>255) bc=255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r,g,b);
    }
%>
<%
    //设置页面不缓存
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);

    //在内存中创建图像
    String num = request.getParameter("num");
    //String[] color = request.getParameterValues("color"); //有多个值时（name可重复）
    int counter = num == null ? (int)(Math.random()*100) : Integer.parseInt(num);
    ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
    cs.setColorFactory(new SingleColorFactory(new Color(25, 60, 170)));
    switch (counter % 5)
    {
        case 0:
            cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
            break;
        case 1:
            cs.setFilterFactory(new MarbleRippleFilterFactory());
            break;
        case 2:
            cs.setFilterFactory(new DoubleRippleFilterFactory());
            break;
        case 3:
            cs.setFilterFactory(new WobbleRippleFilterFactory());
            break;
        case 4:
            cs.setFilterFactory(new DiffuseRippleFilterFactory());
            break;
    }
    BufferedImage image = cs.getCaptcha().getImage();

    // 输出图象到页面
    ImageIO.write(image, "png", response.getOutputStream());
    //加上下面代码,运行时才不会出现java.lang.IllegalStateException: getOutputStream() has already been called ..........等异常
    response.getOutputStream().flush();
    response.getOutputStream().close();
    response.flushBuffer();
    out.clear();
    out = pageContext.pushBody();
%>
